package com.jiedeng.controller.index;

import com.jiedeng.dao.ICheckCountRepository;
import com.jiedeng.dao.IProjectCorpRepository;
import com.jiedeng.dao.IProjectRepository;
import com.jiedeng.mapper.ReportMapper;
import com.jiedeng.model.*;
import com.jiedeng.util.DatetimeUtil;
import com.jiedeng.util.ExcelUtil;
import com.jiedeng.util.POIUtils;
import com.jiedeng.util.QiniuUtil;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import okio.BufferedSink;
import okio.BufferedSource;
import okio.Okio;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.Region;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 统计报表
 *
 * @author zhouyb
 * 2018/4/13.
 */
@RestController
@Scope("prototype")
@RequestMapping("/statisticsReport")
public class StatisticsReportController {
    private final Logger log = LoggerFactory.getLogger(StatisticsReportController.class);
    @Autowired
    ReportMapper reportMapper;

    @Autowired
    IProjectRepository projectRepository;
    @Autowired
    ICheckCountRepository checkCountRepository;
    @Value("${config.prefix}")
    private String prefix;
    @Value("${config.winReporterPath}")
    private String winPath;

    @Value("${config.linuxReporterPath}")
    private String linuxPath;
    @Value("${config.statisticsTempPath}")
    private String statisticsTempPath;

    /**
     * 统计表
     *
     * @param corpId
     * @param postId
     * @return
     */
    @RequestMapping("statisticsDetails")
    public List<Map<String, Object>> statisticsDetails(Long corpId, Long postId) {
        List<Project> projectCorpList = projectRepository.findProjectByCorpIdSQL(corpId);
        List<Map<String, Object>> projectList = new ArrayList<>(10);
        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        for (Project project : projectCorpList) {
            Map<String, Object> projectMap = new HashMap<>(5);
            projectMap.put("projectName", project.getCaption());
            //检查项list
            List<Map<String, Object>> inspectList = reportMapper.statisticsReportInspect(project.getId(), postId);
            List<Map<String, Object>> inspectItemList = new ArrayList<>(10);
            for (Map<String, Object> inspect : inspectList) {
                List<CheckCount> checkCountList = checkCountRepository.findByCheckIdAndCorpWeightLevel(inspect.get("ID") + "",
                        "主要责任单位");
                double scoring = 0.0;
//                double scoring = Double.parseDouble(inspect.get("Weighting")+"");
                if (checkCountList != null && checkCountList.size() > 0) {

                    boolean scoringCheck = true;
                    boolean scoring1Check = true;
                    for (CheckCount checkCount : checkCountList) {
                        if (!scoring1Check && !scoringCheck) {
                            break;
                        }
                        if (scoringCheck && !StringUtils.isEmpty(checkCount.getScoring()) && Double.parseDouble(checkCount.getScoring()) > 0) {
                            scoring -= Double.parseDouble(checkCount.getScoring());
                            scoringCheck = false;
                        }
                        if (scoring1Check && !StringUtils.isEmpty(checkCount.getScoring1()) && Double.parseDouble(checkCount.getScoring1()) > 0) {
                            scoring += Double.parseDouble(checkCount.getScoring1());
                            scoring1Check = false;
                        }
                    }

                }

                inspect.put("scoring", decimalFormat.format(scoring));
                inspect.put("checkCountList", checkCountList);
                inspectItemList.add(inspect);
            }
            if (inspectItemList.size() > 0) {
                projectMap.put("inspectItemList", inspectItemList);
                projectList.add(projectMap);
            }

        }
        // List<Map<String, Object>> countList=reportMapper.detailedReport(projectId);
        return projectList;
    }

    /**
     * 生成统计表
     *
     * @param corpId
     * @param postId
     * @return
     */
    @RequestMapping(value = "statisticsReport",produces="text/html; charset=UTF-8")
    public String statisticsReport(Long corpId, Long postId) {
        String path = "";
        String os = System.getProperty("os.name");
        if (os.toLowerCase().startsWith("win")) {
            path = winPath;
        } else {
            path = linuxPath;
        }
//        String keyName = "统计表20180830.xlsx";
        String keyName = "统计表" + DatetimeUtil.getDateyyyyMMddhhmmss() + ".xlsx";
        // String keyName ="zhenggaibihuandan"+ DatetimeUtil.getDateyyyyMMddhhmmss() + ".xlsx";
        String fileName = path + keyName;
        ExcelUtil.downloadSmallFile(statisticsTempPath, fileName);
        FileInputStream in = null;
        XSSFWorkbook wb = null;
        try {

            in = new FileInputStream(fileName);
            wb = new XSSFWorkbook(in);
            int sheetNo = 0;
            XSSFSheet sheet = wb.getSheetAt(sheetNo);
            Row row = sheet.getRow(1);
            Cell cell = row.createCell(0);
            //右对齐
            CellStyle cellStyle = wb.createCellStyle();
            //自适应
            cellStyle.setWrapText(true);
            //垂直对齐
            cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
            // 设置边框样式
            cellStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
            cellStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
            cellStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
            cellStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);
            cell.setCellStyle(cellStyle);
            List<Map<String, Object>> statisticsDetails = statisticsDetails(corpId, postId);
            DecimalFormat decimalFormat = new DecimalFormat("0.00");
            if (statisticsDetails != null && statisticsDetails.size() > 0) {
                int i = 2;
                for (Map<String, Object> statisticsDetail : statisticsDetails) {
//                    ++i;
                    int n = i;
                    List<Map<String, Object>> inspectItemList = (List<Map<String, Object>>) statisticsDetail.get("inspectItemList");
                    //起始行,结束行,起始列,结束列
                    CellRangeAddress callRangeAddress = new CellRangeAddress(i, i + inspectItemList.size() - 1, 0, 3);
                    sheet.addMergedRegion(callRangeAddress);
                    row = sheet.getRow(i);
                    if (row == null) {
                        row = sheet.createRow(i);
                    }
                    ExcelUtil.createCell(wb, row, (short) 0, statisticsDetail.get("projectName").toString(), XSSFCellStyle.ALIGN_CENTER, XSSFCellStyle.VERTICAL_CENTER);
                    for (Map<String, Object> inspectItemMap : inspectItemList) {
                        CellRangeAddress callRangeAddress1 = new CellRangeAddress(i, i, 4, 7);
                        CellRangeAddress callRangeAddress2 = new CellRangeAddress(i, i, 11, 14);
                        CellRangeAddress callRangeAddress3 = new CellRangeAddress(i, i, 15, 16);
                        sheet.addMergedRegion(callRangeAddress1);
                        sheet.addMergedRegion(callRangeAddress2);
                        sheet.addMergedRegion(callRangeAddress3);
                        row = sheet.getRow(i);
                        if (row == null) {
                            row = sheet.createRow(i);
                        }
                        ExcelUtil.createCell(wb, row, (short) 4, inspectItemMap.get("checkItem_Demand").toString(), XSSFCellStyle.ALIGN_CENTER, XSSFCellStyle.VERTICAL_CENTER);
                        ExcelUtil.createCell(wb, row, (short) 8, inspectItemMap.get("Weighting").toString(), XSSFCellStyle.ALIGN_CENTER, XSSFCellStyle.VERTICAL_CENTER);
                        double scoring = 0.0;
                        if (!StringUtils.isEmpty(inspectItemMap.get("scoring"))) {
                            scoring = (Double.parseDouble(inspectItemMap.get("Weighting").toString()) +
                                    Double.parseDouble(inspectItemMap.get("scoring").toString()));
                        }
                        ExcelUtil.createCell(wb, row, (short) 10, decimalFormat.format(scoring), XSSFCellStyle.ALIGN_CENTER, XSSFCellStyle.VERTICAL_CENTER);
                        ExcelUtil.createCell(wb, row, (short) 11, inspectItemMap.get("Expression_Desc").toString(), XSSFCellStyle.ALIGN_CENTER, XSSFCellStyle.VERTICAL_CENTER);
                        ExcelUtil.createCell(wb, row, (short) 15, inspectItemMap.get("Check_time").toString(), XSSFCellStyle.ALIGN_CENTER, XSSFCellStyle.VERTICAL_CENTER);
                        List<CheckCount> checkCountList = (List<CheckCount>) inspectItemMap.get("checkCountList");
                        String personName = "";
                        Map map = new HashMap(3);
                        for (CheckCount checkCount : checkCountList) {
                            if (!map.containsKey(checkCount.getName())) {
                                personName = personName + checkCount.getName();
//                                personName = personName + checkCount.getCorpCaption() + " - " + checkCount.getName();
                                personName += "\n";
                                map.put(checkCount.getName(), checkCount);
                            }
                        }
                        ExcelUtil.createCell(wb, row, (short) 9, personName, XSSFCellStyle.ALIGN_CENTER, XSSFCellStyle.VERTICAL_CENTER);
                        //水平对齐
                        cellStyle.setAlignment(XSSFCellStyle.ALIGN_LEFT);
                        ExcelUtil.setRegionStyle(sheet, new Region(i, (short) 4, i, (short) 7), cellStyle);
                        ExcelUtil.setRegionStyle(sheet, new Region(i, (short) 11, i, (short) 14), cellStyle);
                        ExcelUtil.setRegionStyle(sheet, new Region(i, (short) 15, i, (short) 16), cellStyle);
                        i++;
                    }
                    //水平对齐
                    cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
                    ExcelUtil.setRegionStyle(sheet, new Region(n, (short) 0, n + inspectItemList.size() - 1, (short) 3), cellStyle);
                }
            }
            FileOutputStream out = new FileOutputStream(fileName);
            wb.write(out);
            in.close();
            out.close();
            QiniuUtil qiniuUtil = new QiniuUtil();
            qiniuUtil.upload(fileName, keyName);
            return prefix + keyName;
        } catch (Exception e) {
//            System.out.println(e.toString());
            log.error("统计表出错", e);
            return "server error";
        } finally {
            try {
                in.close();
            } catch (Exception e) {
                log.error(e.toString());
            }
        }

    }

}
